/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package conexao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.JOptionPane;

/**
 *
 * @author fumio
 */
public class Conexao {

    private static EntityManagerFactory emf = null;
    private static EntityManager em = null;

    private static EntityManager getEm() {
        try {
            if (em == null) {
                emf = Persistence.createEntityManagerFactory("FastHairPU");
                em = emf.createEntityManager();
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        return em;
    }

    private static void beginTransaction() {
        getEm().getTransaction().begin();
    }

    private static void endTransaction() {
        getEm().getTransaction().commit();
    }

    private static void rollbackTransaction() {
        getEm().getTransaction().rollback();
    }
    
    private static boolean persistBanco(Object o){
        try {
           beginTransaction();
           getEm().persist(o);
           endTransaction();
           return true;
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    private static List sqlTransaction(String sql) {
        Query query = null;
        try {
            query = getEm().createQuery(sql);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        System.out.println(query.getResultList());
        return query.getResultList();
    }

    protected static List executarQuery(String sql) {
        return sqlTransaction(sql);
    }
    
    protected static boolean executarPersist(Object o){
        return persistBanco(o);
    }

}
